//
//  LiveRoomViewController.m
//  OpenLive
//
//  Created by GongYuhua on 2016/9/12.
//  Copyright © 2016年 Agora. All rights reserved.
//

#import "LiveRoomViewController.h"
#import "VideoSession.h"
#import "VideoViewLayouter.h"
#import "KeyCenter.h"

//原IM部分
#import "TCMsgHandler.h"
#import "TCMsgModel.h"
#import "TCLoginModel.h"
#import "CWStatusBarNotification.h"
#import "EndLiveViewController.h"

// 豪华礼物展示
#import "redCar.h"
#import "planView.h"
#import "flowerAction.h"
#import "shipAction.h"


// 礼物展示
#import "PresentView.h"
#import "PresentModel.h"
#import "CustonCell.h"
#import "CustonCell.h"
#import "ADViewCell.h"

#import "WKWebViewController.h"

@interface LiveRoomViewController () <AgoraRtcEngineDelegate, TCPushDecorateDelegate, ITCLivePlayListener, PresentViewDelegate,
	UITableViewDelegate, UITableViewDataSource, ADViewCellDelegate>
@property (weak, nonatomic) IBOutlet UILabel *roomNameLabel;
@property (weak, nonatomic) IBOutlet UIView *remoteContainerView;
@property (weak, nonatomic) IBOutlet UIButton *broadcastButton;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *sessionButtons;
@property (weak, nonatomic) IBOutlet UIButton *audioMuteButton;
@property (weak, nonatomic) IBOutlet UIButton *enhancerButton;

@property (strong, nonatomic) AgoraRtcEngineKit *rtcEngine;
@property (assign, nonatomic) BOOL isBroadcaster;
@property (assign, nonatomic) BOOL isMuted;
@property (assign, nonatomic) BOOL shouldEnhancer;
@property (strong, nonatomic) NSMutableArray<VideoSession *> *videoSessions;
@property (strong, nonatomic) VideoSession *fullSession;
@property (strong, nonatomic) VideoViewLayouter *viewLayouter;

@end

@implementation LiveRoomViewController
{
	BOOL _camera_switch;
	float  _beauty_level;
	float  _whitening_level;
	float  _eye_level;
	float  _face_level;
	BOOL _torch_switch;
	BOOL _isMirror;
	
	unsigned long long  _startTime;
	unsigned long long  _lastTime;
	
	NSString*       _logMsg;
	NSString*       _tipsMsg;
	NSString*       _testPath;
	BOOL            _isPreviewing;
	
	BOOL       _appIsInterrupt;
	
	BOOL        _firstAppear;
	

	UIView             *_videoParentView;
	
	AVIMMsgHandler *_msgHandler;
	
	CWStatusBarNotification *_notification;
	
	redCar                  *_car;  // 豪华礼物
	planView                *_plan;
	flowerAction            *_flow;
	shipAction              *_ship;
	
	PresentView             *_presentView; // 礼物展示
	NSMutableArray *expensiveGiftCount;//记录豪华礼物数量
	NSTimer *expensiveGiftTime;//豪华礼物定时器
	
	UITableView *adView;
	ADViewCell *currentCell;
	NSMutableArray *adInfoArr;
	NSMutableArray *adInfoInQueueArr;
	NSInteger endAnimate;
}
static int haohuaCount = 0;//判断上次豪华礼物

- (BOOL)isBroadcaster {
    return self.clientRole == AgoraClientRoleBroadcaster;
}

- (VideoViewLayouter *)viewLayouter {
    if (!_viewLayouter) {
        _viewLayouter = [[VideoViewLayouter alloc] init];
    }
    return _viewLayouter;
}

- (void)setClientRole:(AgoraClientRole)clientRole {
    _clientRole = clientRole;
    
    if (self.isBroadcaster) {
        self.shouldEnhancer = YES;
    }
    [self updateButtonsVisiablity];
}

- (void)setIsMuted:(BOOL)isMuted {
    _isMuted = isMuted;
    [self.rtcEngine muteLocalAudioStream:isMuted];
    [self.audioMuteButton setImage:[UIImage imageNamed:(isMuted ? @"btn_mute_cancel" : @"btn_mute")] forState:UIControlStateNormal];
}

- (void)setVideoSessions:(NSMutableArray<VideoSession *> *)videoSessions {
    _videoSessions = videoSessions;
    if (self.remoteContainerView) {
        [self updateInterfaceWithAnimation:YES];
    }
}

- (void)setFullSession:(VideoSession *)fullSession {
    _fullSession = fullSession;
    if (self.remoteContainerView) {
        [self updateInterfaceWithAnimation:YES];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
	[self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
	[self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.videoSessions = [[NSMutableArray alloc] init];
	
    [self updateButtonsVisiablity];
    _logicView = [[TCPushDecorateView alloc] initWithFrame:self.view.frame];
    _logicView.delegate = self;
    [self.view addSubview:_logicView];
    for (UIButton *button in self.sessionButtons) {
        [_logicView addSubview:button];
    }
	if (self.isEnterSelf) {
		[self enterSelfLive];
	}
	else {
		[self createLive];
	}
    [self getMallInfo];
	
	//礼物
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showGift:)name:@"showGift" object:nil];
	
	_presentView.hidden = YES;
	
	_presentView = [[PresentView alloc] initWithFrame:CGRectMake(0, SH(4), 200, 200)];
	//    _presentView.y = self.view.centerY-100;
	[_logicView addSubview:_presentView];
	_presentView.backgroundColor = kClearColor;
	_presentView.delegate = self;
	
	expensiveGiftCount = [[NSMutableArray alloc] init];
	
	//自定义广告(特殊礼物)View
	adInfoArr = [[NSMutableArray alloc] init];
	adInfoInQueueArr = [[NSMutableArray alloc] init];
	adView = [[UITableView alloc] initWithFrame:CGRectMake(0, SH(3)+80, 252, 110) style:UITableViewStylePlain];
	adView.backgroundColor = kWhiteColor;
	adView.hidden = YES;
	[_logicView addSubview:adView];
	[_logicView sendSubviewToBack:adView];
	adView.delegate = self;
	adView.dataSource  = self;
	[adView registerNib:[UINib nibWithNibName:@"ADViewCell" bundle:nil] forCellReuseIdentifier:@"adCell"];
	adView.delaysContentTouches = NO;
	for (id obj in adView.subviews) {
		if ([obj respondsToSelector:@selector(setDelaysContentTouches:)]) {
			[obj setDelaysContentTouches:NO];
		}
	}
	
}

- (IBAction)doSwitchCameraPressed:(UIButton *)sender {
    [self.rtcEngine switchCamera];
}

- (IBAction)doMutePressed:(UIButton *)sender {
    self.isMuted = !self.isMuted;
}

- (IBAction)doBroadcastPressed:(UIButton *)sender {
    if (self.isBroadcaster) {
        self.clientRole = AgoraClientRoleAudience;
        if (self.fullSession.uid == 0) {
            self.fullSession = nil;
        }
    } else {
        self.clientRole = AgoraClientRoleBroadcaster;
    }
    
    [self.rtcEngine setClientRole:self.clientRole];
    [self updateInterfaceWithAnimation:YES];
}

- (IBAction)doDoubleTapped:(UITapGestureRecognizer *)sender {
    NSLog(@"切换大小窗被调用了");
    if (!self.fullSession) {
        VideoSession *tappedSession = [self.viewLayouter responseSessionOfGesture:sender inSessions:self.videoSessions inContainerView:self.remoteContainerView];
        if (tappedSession) {
            self.fullSession = tappedSession;
        }
    } else {
        self.fullSession = nil;
    }
}

- (IBAction)doLeavePressed:(UIButton *)sender {
	if (self.clientRole == AgoraClientRoleBroadcaster) {
		[self closeVC];
	}
    [self leaveChannel];
}

- (void)updateButtonsVisiablity {
    [self.broadcastButton setImage:[UIImage imageNamed:self.isBroadcaster ? @"btn_join_cancel" : @"btn_join"] forState:UIControlStateNormal];
    for (UIButton *button in self.sessionButtons) {
        button.hidden = !self.isBroadcaster;
    }
}

- (void)leaveChannel {
    [self setIdleTimerActive:YES];
    
    [self.rtcEngine setupLocalVideo:nil];
    [self.rtcEngine leaveChannel:nil];
    if (self.isBroadcaster) {
        [self.rtcEngine stopPreview];
    }
    
    for (VideoSession *session in self.videoSessions) {
        [session.hostingView removeFromSuperview];
    }
    [self.videoSessions removeAllObjects];
    
    /*
    if ([self.delegate respondsToSelector:@selector(liveVCNeedClose:)]) {
        [self.delegate liveVCNeedClose:self];
    }
     */
    EndLiveViewController *endVC = [[EndLiveViewController alloc] init];
    
    [self presentViewController:endVC animated:YES completion:nil];
}

- (void)setIdleTimerActive:(BOOL)active {
    [UIApplication sharedApplication].idleTimerDisabled = !active;
}

- (void)alertString:(NSString *)string {
    if (!string.length) {
        return;
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:string preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)updateInterfaceWithAnimation:(BOOL)animation {
    if (animation) {
        [UIView animateWithDuration:0.3 animations:^{
            [self updateInterface];
            [self.view layoutIfNeeded];
        }];
    } else {
        [self updateInterface];
    }
}

- (void)updateInterface {
    NSArray *displaySessions;
    if (!self.isBroadcaster && self.videoSessions.count) {
        displaySessions = [self.videoSessions subarrayWithRange:NSMakeRange(1, self.videoSessions.count - 1)];
    } else {
        displaySessions = [self.videoSessions copy];
    }
    
    [self.viewLayouter layoutSessions:displaySessions fullSession:self.fullSession inContainer:self.remoteContainerView];
    [self setStreamTypeForSessions:displaySessions fullSession:self.fullSession];
}

- (void)setStreamTypeForSessions:(NSArray<VideoSession *> *)sessions fullSession:(VideoSession *)fullSession {
    if (fullSession) {
        for (VideoSession *session in sessions) {
            [self.rtcEngine setRemoteVideoStream:session.uid type:(session == self.fullSession ? AgoraVideoStreamTypeHigh : AgoraVideoStreamTypeLow)];
        }
    } else {
        for (VideoSession *session in sessions) {
            [self.rtcEngine setRemoteVideoStream:session.uid type:AgoraVideoStreamTypeHigh];
        }
    }
}

- (void)addLocalSession {
    VideoSession *localSession = [VideoSession localSession];
    [self.videoSessions addObject:localSession];
    [self.rtcEngine setupLocalVideo:localSession.canvas];
    [self updateInterfaceWithAnimation:YES];
}

- (VideoSession *)fetchSessionOfUid:(NSUInteger)uid {
    for (VideoSession *session in self.videoSessions) {
        if (session.uid == uid) {
            return session;
        }
    }
    return nil;
}

- (VideoSession *)videoSessionOfUid:(NSUInteger)uid {
    VideoSession *fetchedSession = [self fetchSessionOfUid:uid];
    if (fetchedSession) {
        return fetchedSession;
    } else {
        VideoSession *newSession = [[VideoSession alloc] initWithUid:uid];
        [self.videoSessions addObject:newSession];
        [self updateInterfaceWithAnimation:YES];
        return newSession;
    }
}

//MARK: - Agora Media SDK
- (void)loadAgoraKit {
    self.rtcEngine = [AgoraRtcEngineKit sharedEngineWithAppId:[KeyCenter AppId] delegate:self];
    [self.rtcEngine setChannelProfile:AgoraChannelProfileLiveBroadcasting];
    [self.rtcEngine enableDualStreamMode:YES];
    [self.rtcEngine enableVideo];
    [self.rtcEngine setVideoProfile:self.videoProfile swapWidthAndHeight:YES];
    [self.rtcEngine setClientRole:self.clientRole];
    
    if (self.isBroadcaster) {
        [self.rtcEngine startPreview];
    }
    
    [self addLocalSession];
    [self.rtcEngine enableWebSdkInteroperability:YES];
    int code = [self.rtcEngine joinChannelByToken:nil channelId:self.channelId info:nil uid:0 joinSuccess:nil];
    if (code == 0) {
        [self setIdleTimerActive:NO];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self alertString:[NSString stringWithFormat:@"Join channel failed: %d", code]];
        });
    }
    
    if (self.isBroadcaster) {
        self.shouldEnhancer = YES;
    }
}

- (void)rtcEngine:(AgoraRtcEngineKit *)engine didJoinedOfUid:(NSUInteger)uid elapsed:(NSInteger)elapsed {
    VideoSession *userSession = [self videoSessionOfUid:uid];
    [self.rtcEngine setupRemoteVideo:userSession.canvas];
}

- (void)rtcEngine:(AgoraRtcEngineKit *)engine firstLocalVideoFrameWithSize:(CGSize)size elapsed:(NSInteger)elapsed {
    if (self.videoSessions.count) {
        [self updateInterfaceWithAnimation:NO];
    }
}

- (void)rtcEngine:(AgoraRtcEngineKit *)engine didOfflineOfUid:(NSUInteger)uid reason:(AgoraUserOfflineReason)reason {
    VideoSession *deleteSession;
    for (VideoSession *session in self.videoSessions) {
        if (session.uid == uid) {
            deleteSession = session;
        }
    }
    
    if (deleteSession) {
        [self.videoSessions removeObject:deleteSession];
        [deleteSession.hostingView removeFromSuperview];
        [self updateInterfaceWithAnimation:YES];
        
        if (deleteSession == self.fullSession) {
            self.fullSession = nil;
        }
    }
}

-(void)closeVC{
    /*
    [[NetworkTool sharedTool] requestWithName:@"删除直播" URLString:APICreateLives parameters:nil method:@"DELETE" callBack:^(id responseObject) {
        NSDictionary *dict = responseObject[@"data"];
        [self leaveChannel];
    }];
     */
    [self leaveChannel];
}

#pragma mark 原腾讯直播间方法
-(void)clickScreen:(UITapGestureRecognizer *)gestureRecognizer{
    
}

- (void)enterSelfLive
{
	NSDictionary *userInfo = GetUserDefaule(USERINFO);
	_liveInfo.userinfo.headpic = userInfo[@"face"];
	_liveInfo.userinfo.nickname = userInfo[@"nickname"];
	
	[self loadAgoraKit];
	
	TCPublishInfo *info = [[TCPublishInfo alloc] init];
	info.liveInfo = _liveInfo;
	info.msgHandler  =  _msgHandler;
	[_logicView setPublishInfo:info];
}

- (void)createLive
{
    if (self.clientRole == AgoraClientRoleBroadcaster) {
        NSDictionary *userInfo = GetUserDefaule(USERINFO);
        _liveInfo.userinfo.headpic = userInfo[@"face"];
        _liveInfo.userinfo.nickname = userInfo[@"nickname"];
        NSLog(@"live info is %@", _liveInfo);
        __weak typeof(self) weakSelf = self;
        _msgHandler = [[AVIMMsgHandler alloc] init];
        [_msgHandler createLiveRoomWithTitle:_liveInfo.title coverPic:_liveInfo.userinfo.frontcover tagId:_liveInfo.tag handler:^(int errCode, NSString *groupId, NSString *pusherUrl, NSInteger timestamp, NSString *rooId) {
            
            NSString *userId = [[TCLoginModel sharedInstance] getLoginParam].identifier;
            NSLog(@"创建直播 errCode = %d, groupId = %@, pusherUrl = %@, timestamp = %ld， useriD = %@", errCode, groupId, pusherUrl, (long)timestamp, userId);
            
            if (errCode == 0)
            {
                // 保存直播信息，后面用到
                NSDictionary *live = @{@"hostId":userId, @"groupId":groupId};
                SetUserDefaule(live, CURRLIVE);
                
                _liveInfo.groupid = groupId;    //这一个是创建直播间接口返回data里叫“chatroom_id”的字段
                _liveInfo.playurl = pusherUrl;
                _liveInfo.roomid = rooId;       //这一个是创建直播间接口返回data里叫“id”的字段
                //拿到GroupID作为roomName
                self.channelId = groupId;
				
                [self loadAgoraKit];
                
                TCPublishInfo *info = [[TCPublishInfo alloc] init];
                info.liveInfo = _liveInfo;
                info.msgHandler  =  _msgHandler;
                [_logicView setPublishInfo:info];
                
                /*
                 //状态初始化
                 _camera_switch = NO;
                 _beauty_level = 9;
                 _whitening_level = 3;
                 [_txLivePublisher setBeautyFilterDepth:_beauty_level setWhiteningFilterDepth:_whitening_level];
                 _torch_switch= NO;
                 _log_switch = NO;
                 _isMirror = NO;
                 
                 //启动rtmp
                 _rtmpUrl =  _liveInfo.playurl;
                 _liveInfo.timestamp = (int)timestamp;
                 [weakSelf startRtmp];
                 */
            }
            else
            {
                [_logicView closeVCWithError:[NSString stringWithFormat:@"%@%d",kErrorMsgCreateGroupFailed, errCode]  Alert:YES Result:NO];
            }
        }];
    }
}
- (void)getMallInfo
{
    _mall = [[MallInLiveViewController alloc] init];
    _mall.uidForMall = [GetUserDefaule(USERINFO) valueForKey:@"user_id"];
    _mall.delegate = self;
    [self addChild:_mall inRect:_mall.view.frame];
    [self.logicView addSubview:_mall.view];
}


- (void)presentDetailMall
{
    
}

- (void)showGift:(NSNotification *)notification {
	
	NSDictionary *gift = notification.userInfo;
	
	NSLog(@"--接收到展示礼物的消息通知--\n%@", gift);
	//    NSError *err;
	//    NSData *jsonData = [gift[@"msg"] dataUsingEncoding:NSUTF8StringEncoding];
	//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
	//                                                        options:NSJSONReadingMutableContainers
	//                                                          error:&err];
	NSDictionary *dic = gift[@"msg"];
	NSLog(@"%@", dic);
	static int count = 0;
	NSString *giftType;
	//    if ([dic[@"type"] isEqual:@(0)]) {
	if ([[dic valueForKey:@"type"] isEqualToString:@"0"]) {
		giftType = [NSString stringWithFormat:@"%@_%d", dic[@"giftname"], count];
	}
	else if([[dic valueForKey:@"type"] isEqualToString:@"1"]){
		giftType = dic[@"giftname"];
	}
	else {
		[adInfoInQueueArr addObject:dic];
		if (adInfoArr.count == 0) {
			[adInfoArr addObject:dic];
			[adView reloadData];
			[self checkAdGift];
		}
		return;
	}
	count++;
	
	/**
	 GSPChatMessage *msg = [[GSPChatMessage alloc] init];
	 msg.text = [NSString stringWithFormat:@"赠送%@", dic[@"name"]];
	 msg.senderChatID = giftType;
	 msg.senderName = gift[@"nickName"];
	 // 礼物模型
	 GiftModel *giftModel = [[GiftModel alloc] init];
	 giftModel.headImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:gift[@"headPic"]]]];
	 giftModel.name = msg.senderName;
	 giftModel.giftImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:dic[@"gifticon"]]]];
	 giftModel.giftName = dic[@"giftname"];
	 giftModel.giftCount = 1;
	 
	 AnimOperationManager *manager = [AnimOperationManager sharedManager];
	 manager.parentView = self.view;
	 // 用用户唯一标识 msg.senderChatID 存礼物信息,model 传入礼物模型
	 [manager animWithUserID:[NSString stringWithFormat:@"%@-%@", gift[@"userId"], msg.senderChatID] model:giftModel finishedBlock:^(BOOL result) {
	 
	 NSLog(@"动画 block = %d", result);
	 
	 }];
	 */
	
	_presentView.hidden = NO;
	
	// 是否叠加的礼物
	PresentModel *giftModel = [PresentModel modelWithSender:gift[@"nickName"] giftName:dic[@"giftname"] icon:gift[@"headPic"] giftImageName:dic[@"gifticon"]];
	// 是否叠加的礼物
	if ([[NSString stringWithFormat:@"%@", dic[@"type"]] isEqualToString:@"0"]) {
		[_presentView insertPresentMessages:@[giftModel] showShakeAnimation:NO];
	}
	else
		[_presentView insertPresentMessages:@[giftModel] showShakeAnimation:YES];
	
	//    BOOL contin;
	//    if (dic[@"type"] == 0) {
	//        contin = NO;
	//    }
	//    else
	//        contin = YES;
	//
	//    PresentModel *giftModel = [PresentModel modelWithSender:gift[@"nickName"] giftName:dic[@"giftname"] icon:gift[@"headPic"] giftImageName:dic[@"gifticon"]];
	//    [_presentView insertPresentMessages:@[giftModel] showShakeAnimation:contin];
	
	// 写死 9 跑车 19 飞机 21 游轮 22 烟花
	//    if ([dic[@"id"] isEqualToString:@"9"]) {
	//        _car = [[redCar alloc]initWithIcons:gift[@"headPic"]  andName:gift[@"nickName"]];
	//        [self.view addSubview:_car];
	//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
	//            [_car removeFromSuperview];
	//        });
	//    }
	//    else if ([dic[@"id"] isEqualToString:@"19"]) {
	//        _plan = [[planView alloc]initWithicon:gift[@"headPic"] andName:gift[@"nickName"]];
	//        _plan.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/2);
	//        [self.view addSubview:_plan];
	//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
	//            [_plan removeFromSuperview];
	//        });
	//    }
	//    else if ([dic[@"id"] isEqualToString:@"21"]) {
	//        _ship = [[shipAction alloc] initWithName:gift[@"nickName"] and:gift[@"headPic"]];
	//        [self.view addSubview:_ship];
	//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
	//            [_ship removeFromSuperview];
	//        });
	//    }
	//    else if ([dic[@"id"] isEqualToString:@"22"]) {
	//        _flow = [[flowerAction alloc]init];
	//        [self.view addSubview:_flow];
	//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
	//            [_flow removeFromSuperview];
	//        });
	//    }
	
	if (  [dic[@"id"] isEqualToString:@"22"] || [dic[@"id"] isEqualToString:@"21"] || [dic[@"id"] isEqualToString:@"9"] || [dic[@"id"] isEqualToString:@"19"]) {
		
		[self expensiveGift:gift];
	}
	
}
-(void)expensiveGift:(NSDictionary *)giftData{
	
	if (giftData == nil) {
	}
	else
	{
		[expensiveGiftCount addObject:giftData];
	}
	if(haohuaCount == 0){
		[self enGiftEspensive];
	}
}
-(void)enGiftEspensive{
	
	if (expensiveGiftCount.count == 0 || expensiveGiftCount == nil) {//判断队列中有item且不是满屏
		
		[expensiveGiftTime invalidate];
		
		expensiveGiftTime = nil;
		
		return;
		
	}
	
	NSDictionary *Dic = [expensiveGiftCount firstObject];
	
	[expensiveGiftCount removeObjectAtIndex:0];
	
	[self expensiveGiftPopView:Dic];
	
	
}
-(void)expensiveGiftPopView:(NSDictionary *)giftData{
	
	
	
	NSNumber *numbers = [giftData[@"msg"] valueForKey:@"id"];
	
	int number = [numbers intValue];
	
	if (number == 22) {
		haohuaCount = 1;
		_flow = [[flowerAction alloc]init];
		NSLog(@"***************************************烟花");
		
		[self.view addSubview:_flow];
		
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
			
			[_flow removeFromSuperview];
			haohuaCount = 0;
			if (expensiveGiftCount.count >0) {
				
				[self expensiveGift:nil];
				
			}
			
		});
	}
	else if (number == 21){
		haohuaCount = 1;
		
		NSLog(@"***************************************邮轮");
		_ship = [[shipAction alloc]initWithName:[giftData valueForKey:@"nickName"] and:[giftData valueForKey:@"headPic"]];
		[self.view addSubview:_ship];
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
			[_ship removeFromSuperview];
			haohuaCount = 0;
			if (expensiveGiftCount.count >0) {
				
				[self expensiveGift:nil];
				
			}
			
			
		});
		
	}
	else if (number == 9){
		haohuaCount = 1;
		
		_car = [[redCar alloc]initWithIcons:[giftData valueForKey:@"headPic"] andName:[giftData valueForKey:@"nickName"]];
		[self.view addSubview:_car];
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
			[_car removeFromSuperview];
			haohuaCount = 0;
			if (expensiveGiftCount.count >0) {
				[self expensiveGift:nil];
				
			}
			
			
		});
	}
	else if (number == 19) {
		haohuaCount = 1;
		
		_plan = [[planView alloc]initWithicon:[giftData valueForKey:@"headPic"] andName:[giftData valueForKey:@"nickName"]];
		_plan.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/2);
		[self.view addSubview:_plan];
		dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
			[_plan removeFromSuperview];
			haohuaCount = 0;
			
			if (expensiveGiftCount.count >0) {
				[self expensiveGift:nil];
				
			}
			
			
		});
	}
	
}

#pragma mark - 豪华礼物队列，防止满屏

#pragma mark - UItableView delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	return 110;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	ADViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"adCell"];
	NSDictionary *info = adInfoArr[indexPath.row];
	cell.info = info;
	cell.delegate = self;
	currentCell = cell;
	return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	NSLog(@"I was selected");
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	NSLog(@"the cell num in here is %ld", adInfoArr.count);
	if (adInfoArr.count > 0) {
		adView.alpha = 1.0;
		adView.hidden = NO;
	}else {
		adView.hidden = YES;
	}
	return adInfoArr.count;
}

- (void)jumpToLink:(NSString *)url
{
	WKWebViewController *vc = [[WKWebViewController alloc] init];
	NSString *urlStr;
	if ([url containsString:@"http"]) {
		urlStr = url;
	}
	else {
		urlStr = [NSString stringWithFormat:@"http://%@",url];
	}
	[vc loadWebURLSring:urlStr];
	[self.navigationController pushViewController:vc animated:YES];
	NSLog(@"jump has been clicked");
}
#pragma mark - PresentViewDelegate

- (PresentViewCell *)presentView:(PresentView *)presentView cellOfRow:(NSInteger)row
{
	return [[CustonCell alloc] initWithRow:row];
}

- (void)presentView:(PresentView *)presentView configCell:(PresentViewCell *)cell model:(id<PresentModelAble>)model
{
	CustonCell *customCell = (CustonCell *)cell;
	customCell.model = model;
}

- (void)presentView:(PresentView *)presentView didSelectedCellOfRowAtIndex:(NSUInteger)index
{
	CustonCell *cell = [presentView cellForRowAtIndex:index];
	NSLog(@"你点击了：%@", cell.model.giftName);
}

- (void)presentView:(PresentView *)presentView animationCompleted:(NSInteger)shakeNumber model:(id<PresentModelAble>)model
{
	NSLog(@"%@礼物的连送动画执行完成", model.giftName);
}

//循环线程检测有无自定义广告礼物
- (void)checkAdGift {
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
		
		if(adInfoArr.count > 0) {
			[adInfoArr removeObjectAtIndex:0];
			[adInfoInQueueArr removeObjectAtIndex:0];
			[UIView animateKeyframesWithDuration:1.0 delay:0.0 options:UIViewKeyframeAnimationOptionAllowUserInteraction animations:^{
				adView.alpha = 0.05;
			} completion:^(BOOL finished) {
				if (finished) {
					if (adInfoInQueueArr.count > 0) {
						[adInfoArr addObject:adInfoInQueueArr[0]];
						[adView reloadData];
						[self checkAdGift];
					}
					[adView reloadData];
				}
			}];
		}
	});
}

@end
